import augeas
import os
import time

class ConfigureMounts:
    def __init__(self, mounts):
        self.mounts = mounts
        self.successful = 0
        self.failed     = 0
        self.oo_sync    = 0

    def configure(self):
        print "\033[1;36m- Configuring Mounts\033[1;m"
        runtime_start = time.time()
        mounts = self.mounts

        a = augeas.Augeas('/')
        matches = a.match('/files/etc/fstab/*/file')
        current_mount_points = list([a.get(match) for match in matches])
        # Get a list for nodes in to a list
        nodes = a.match('/files/etc/fstab/*')
        node_list = list([os.path.basename(node) for node in nodes])

        for mount in mounts:
            mount_point = mounts[mount]['mount-point']
            spec        = mounts[mount]['device-name']
            vfstype     = mounts[mount]['fs-type']
            opt         = mounts[mount]['options']
            dump        = mounts[mount]['dump-freq']
            passno      = mounts[mount]['pass-num']

            if mount_point in current_mount_points:
                # Compare new and existing mount attributes
                # Resolve any differences.
                self.successful += 1
            else:
                print "%s does not exist..creating" % mount_point
                # Get the a new node number. Must get the highest node
                # currently in the tree + 1. Used when create a new node
                # in the tree.
                node = (int(max(node_list)) + 1)
                a.set('/files/etc/fstab/%s/spec' % str(node), spec)
                a.set('/files/etc/fstab/%s/file' % str(node), mount_point)
                a.set('/files/etc/fstab/%s/vfstype' % str(node), vfstype)

                # Split, then assign each option to a different opts index
                # assigning "opt1,opt2" is in error for augeas
                opts = opt.split(',')
                opt_count = 0
                for opt in opts:
                    a.set('/files/etc/fstab/%s/opt[%s]' % (str(node), opt_count), opt)
                    opt_count = opt_count + 1
                # Configure the remaning options
                a.set('/files/etc/fstab/%s/dump' % str(node), dump)
                a.set('/files/etc/fstab/%s/passno' % str(node), passno)
                a.save()
                self.oo_sync += 1
                self.successful += 1

        # Collect Stats
        runtime_end = time.time()
        runtime = (runtime_end - runtime_start)

        stats = {
            'runtime'   : runtime,
            'successful': self.successful,
            'failed'    : self.failed,
            'oo_sync'   : self.oo_sync
        }

        return stats
